<template>
  <div class="content" :class="{ 'is-mobile': isMobile }">
    <heads :current="6"></heads>
    <div class="main">
      <div class="filter-card">
        <el-form :inline="true" class="search-form">
          <el-form-item>
            <el-date-picker
              v-model="searchParams.dateRange"
              type="daterange"
              value-format="yyyy-MM-dd"
              @change="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="searchParams.status_value"
              :placeholder="$t('orderList.status')"
              @change="handleSearch"
            >
              <el-option
                v-for="item in orderStatusOptions"
                :key="item.value"
                :label="$t(`order.${item.label}`)"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <div class="product-list">
        <div class="product-item" v-for="(item, index) in orderList" :key="index" >
          <div class="product-image">
            <img :src="item.ship.post_url" :alt="item.ship.name"/>
          </div>
          <div class="product-info">
            <div style="display: flex;align-items: center;justify-content: space-between">
              <h2 class="product-name">{{ item.ship.name }}</h2>
              <el-tag type="info" v-if="item.status === -1">{{ $t('order.cancel')}}</el-tag>
              <el-tag type="warning" v-else-if="item.status === 0">{{ $t('order.wait_pay')}}</el-tag>
              <el-tag type="success" v-else-if="item.status === 1">{{ $t('order.isBooked')}}</el-tag>
            </div>
            <div class="product-desc">{{ $t('payment.tripDate')}}：{{ item.start_time }}</div>
            <div class="product-desc">{{ $t('order.adult')}}：{{ item.adult_count }}</div>
            <div class="product-desc">{{ $t('order.child')}}：{{ item.child_count }}</div>
            <div class="product-meta">
              <span class="duration">{{ $t('payment.tripDuration') }}：{{ item.ship.duration }}h</span>
            </div>
            <div class="product-footer">
              <div class="price" v-if="item.total_price > 0">
                <template v-if="$store.state.userInfo">
                  <span class="original-price">${{ item.total_price }}</span>
                  <span class="discount">-20%</span>
                  <span class="discount-price">${{ (item.total_price * 0.8).toFixed(2) }}</span>
                </template>
                <template v-else>
                  <span class="amount">${{ item.total_price }}</span>
                </template>
              </div>
              <div class="action-buttons" v-if="item.status_value === 'wait_pay'">
                <div class="countdown" v-if="countdowns[item.id]">
                  {{ $t('payment.timeRemaining') }}: {{ countdowns[item.id] }}
                </div>
                <div class="button-group">
                  <el-button type="primary" size="small" class="" @click="handlePay(item)">
                    {{ $t('order.proceedToPayment') }}
                  </el-button>
                  <el-button type="danger" size="small" class="" @click="handleCancel(item)">
                    {{ $t('order.cancel') }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="pagination">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            :total="total"
            layout="total, sizes, prev, pager, next"
        />
      </div>
    </div>

    <!-- 取消订单确认弹窗 -->
    <el-dialog
      :visible.sync="cancelDialog.visible"
      :title="$t('orderList.cancelConfirmTitle')"
      width="30%"
    >
      <span>{{ $t('orderList.cancelConfirmContent') }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog.visible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="confirmCancel" :loading="cancelDialog.loading">
          {{ $t('common.confirm') }}
        </el-button>
      </span>
    </el-dialog>
    <foot></foot>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { Message } from 'element-ui'
import {http} from "@/api/api";

export default {
  name: 'OrderList',
  data() {
    return {
      isMobile: false,
      loading: false,
      orderList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchParams: {
        dateRange: null,
        status_value: 'wait_pay'
      },
      orderStatusOptions: [
        { value: 'wait_pay', label: 'wait_pay' },
        { value: 'paid', label: 'isBooked' },
        { value: 'canceled', label: 'cancel' }
      ],
      cancelDialog: {
        visible: false,
        loading: false,
        currentOrder: null
      },
      countdowns: {},
      countdownIntervals: {}
    }
  },
  mounted() {
    this.handleSearch()
    this.checkDevice()
    window.addEventListener('resize', this.checkDevice)
  },
  beforeDestroy() {
    // Clear all intervals when component is destroyed
    Object.values(this.countdownIntervals).forEach(interval => {
      clearInterval(interval)
    })
    window.removeEventListener('resize', this.checkDevice)
  },
  methods: {
    checkDevice() {
      this.isMobile = window.innerWidth <= 750
    },
    async fetchOrders() {
      if (!this.$store.state.userInfo) return
      this.loading = true
      try {
        const params = {
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          status_value: this.searchParams.status_value,
          start_time: this.searchParams.dateRange?.[0],
          end_time: this.searchParams.dateRange?.[1],
          userId: this.$store.state.userInfo.id,
          role: 2
        }

        const response = await http.order.page(params)
        this.orderList = response.data.rows
        this.total = response.data.count

        // Start countdowns for wait_pay orders
        this.orderList.forEach(order => {
          if (order.status_value === 'wait_pay') {
            this.startCountdown(order)
          }
        })
      } catch (error) {
        console.error('Failed to fetch orders:', error)
        Message.error(this.$t('orderList.fetchError'))
      } finally {
        this.loading = false
      }
    },
    formatDateTime(date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm')
    },
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD')
    },
    getStatusType(status) {
      const statusMap = {
        pending: 'warning',
        confirmed: 'primary',
        completed: 'success',
        cancelled: 'info'
      }
      return statusMap[status] || 'info'
    },
    canCancel(order) {
      if (!['pending', 'confirmed'].includes(order.status)) {
        return false
      }
      const tripDate = dayjs(order.tripDate)
      const today = dayjs()
      return tripDate.diff(today, 'day') > 1
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchOrders()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchOrders()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchOrders()
    },
    handlePay(order) {
      this.$router.push({
        path: '/payment',
        query: { orderId: order.id }
      })
    },
    handleCancel(order) {
      this.cancelDialog.currentOrder = order
      this.cancelDialog.visible = true
    },
    startCountdown(order) {
      if (order.status_value !== 'wait_pay') return

      const createTime = dayjs(order.create_time)
      const endTime = createTime.add(3, 'minute')

      // Clear existing interval if any
      if (this.countdownIntervals[order.id]) {
        clearInterval(this.countdownIntervals[order.id])
      }

      const updateCountdown = () => {
        const now = dayjs()
        const diff = endTime.diff(now, 'second')

        if (diff <= 0) {
          clearInterval(this.countdownIntervals[order.id])
          this.$delete(this.countdowns, order.id)
          this.fetchOrders() // Refresh orders
          return
        }

        const minutes = Math.floor(diff / 60)
        const seconds = diff % 60
        this.$set(this.countdowns, order.id, `${minutes}:${seconds.toString().padStart(2, '0')}`)
      }

      updateCountdown()
      this.countdownIntervals[order.id] = setInterval(updateCountdown, 1000)
    },
    async confirmCancel() {
      if (!this.cancelDialog.currentOrder) return

      this.cancelDialog.loading = true
      try {
        await http.order.cancel(this.cancelDialog.currentOrder.id)
        Message.success(this.$t('orderList.cancelSuccess'))
        this.cancelDialog.visible = false
        this.fetchOrders()
      } catch (error) {
        // Message.error(this.$t('orderList.cancelError'))
      } finally {
        this.cancelDialog.loading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.content {
  .main {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
    min-height: calc(100vh - 2.5rem);

    @media screen and (max-width: 750px) {
      padding: 10px;
    }
  }
}

.filter-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;

  .search-form {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
  }
}

.product-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.product-item {
  display: flex;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.3s ease;
  border: 1px solid #EEEEEE;
  @media screen and (max-width: 750px) {
    flex-direction: column;
  }
  &:hover {
    transform: translateY(-5px);
  }

  .product-image {
    width: 300px;
    height: 200px;
    flex-shrink: 0;
    padding: 20px 0;

    @media screen and (max-width: 750px) {
      width: 100%;
      height: 180px;
    }

    img {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  }

  .product-info {
    flex: 1;
    padding: 20px;
    display: flex;
    flex-direction: column;

    .product-name {
      font-size: 20px;
      color: #333;
      margin-bottom: 10px;
    }

    .product-desc {
      color: #666;
      font-size: 14px;
      line-height: 1.5;
      margin-bottom: 15px;
    }

    .product-meta {
      color: #666;
      font-size: 14px;
      margin-bottom: 15px;

      .duration {
        display: inline-flex;
        align-items: center;
      }
    }

    .product-footer {
      margin-top: auto;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .price {
        display: flex;
        align-items: center;
        gap: 5px;

        .original-price {
          text-decoration: line-through;
          color: #999;
          font-size: 14px;
        }

        .discount {
          color: #ff4949;
          font-size: 12px;
          background: rgba(255,73,73,0.1);
          padding: 2px 4px;
          border-radius: 2px;
        }

        .discount-price {
          color: #ff4949;
          font-weight: bold;
          font-size: 20px;
        }

        .amount {
          font-size: 20px;
          color: #0F7CD0;
          font-weight: bold;
        }
      }

      .action-buttons {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 8px;

        .countdown {
          font-size: 14px;
          color: #ff4949;
          font-weight: bold;
        }

        .button-group {
          display: flex;
          align-items: center;
          gap: 10px;

          .pay-btn {
            background-color: #0F7CD0;
            border-color: #0F7CD0;
            padding: 8px 20px;
            margin: 0;

            &:hover {
              background-color: darken(#0F7CD0, 5%);
              border-color: darken(#0F7CD0, 5%);
            }
          }

          .cancel-btn {
            color: #666;
            padding: 8px 15px;
            margin: 0;

            &:hover {
              color: #ff4949;
            }
          }
        }
      }
    }
  }
}

.is-mobile {
  .product-item {
    .product-info {
      padding: 15px;

      .product-name {
        font-size: 18px;
      }

      .product-footer {
        flex-direction: column;
        gap: 15px;

        .price {
          align-self: flex-start;
        }

        .action-buttons {
          width: 100%;
          align-items: stretch;

          .button-group {
            flex-direction: column;
            width: 100%;

            .pay-btn, .cancel-btn {
              width: 100%;
              margin: 0;
            }
          }
        }
      }
    }
  }
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media screen and (max-width: 750px) {
  .filter-card {
    padding: 15px;

    .search-form {
      :deep(.el-form-item) {
        margin-bottom: 10px;
      }
    }
  }

  .order-card {
    .order-header {
      padding: 12px 15px;
    }

    .order-content {
      padding: 15px;
    }

    .order-info {
      .info-row {
        .label {
          width: 100px;
        }
      }
    }
  }
}
</style>
